package com.own.component.common.util.verification;

import com.own.component.common.em.GenderEnum;
import com.own.constant.ConstantDateFormatPattern;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;

/**
 * IdCardModel
 *
 * @author chenxueli
 * @date 2024-03-14 13:25:39
 */
@Slf4j
public class IdCardModel {

    private static final IdCardInfo NON_ID_CARD = IdCardInfo.builder()
            .gender(GenderEnum.NULL)
            .build();

    /**
     * 是否是有效的
     */
    @Getter
    private final boolean available;
    /**
     * 身份证号上的基本信息
     */
    private IdCardInfo idCardInfo;

    public IdCardModel(String idCardNo) {
        // 将身份证号转换成18位的身份证
        idCardNo = IdCardUtil.convert15CardTo18(idCardNo);
        if (idCardNo == null || !IdCardUtil.validateCard(idCardNo)) {
            this.available = false;
            return;
        }
        var birth = IdCardUtil.getBirthByIdCard(idCardNo);
        if (birth == null) {
            this.available = false;
            return;
        }
        this.available = true;
        var gender = IdCardUtil.getGenderByIdCard(idCardNo);
        var age = IdCardUtil.getAgeByIdCard(idCardNo);
        var province = IdCardUtil.getProvinceByIdCard(idCardNo);
        var birthday = LocalDate.parse(birth, ConstantDateFormatPattern.Formatter.YYYY_MM_DD);
        this.idCardInfo = IdCardInfo.builder()
                .gender(gender)
                .province(province)
                .age(age)
                .birthday(birthday)
                .year(birthday.getYear())
                .month(birthday.getMonthValue())
                .day(birthday.getDayOfMonth())
                .build();
    }

    public IdCardInfo getIdCardInfo() {
        if (available) {
            return idCardInfo;
        }
        return NON_ID_CARD;
    }

    @Getter
    @Builder
    public static class IdCardInfo {
        /**
         * 性别信息
         */
        private final GenderEnum gender;
        /**
         * 今年的年龄
         */
        private final int age;
        /**
         * 出生年份
         */
        private final int year;
        /**
         * 出生月份
         */
        private final int month;
        /**
         * 出生日
         */
        private final int day;
        /**
         * 生日
         */
        private final LocalDate birthday;
        /**
         * 省份
         */
        private final String province;
    }

}
